package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.holder.UserHolder;
import com.leyou.common.utils.JsonUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "cart:uid:";

    public void addItemToCart(Cart cart) {
        // 1.获取用户
        UserInfo user = UserHolder.getUserInfo();
        // 2.获取Hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(KEY_PREFIX + user.getId());
        // 3.判断商品是否存在
        String skuId = cart.getSkuId().toString();
        Boolean exists = hashOps.hasKey(skuId);
        if (BooleanUtils.isTrue(exists)) {
            int num = cart.getNum();
            // 4.存在，修改数量
            String json = hashOps.get(skuId);
            // 取出reids中商品
            cart = JsonUtils.toBean(json, Cart.class);
            // 修改数量
            cart.setNum(cart.getNum() + num);
        }
        // 5.写入redis
        hashOps.put(skuId, JsonUtils.toString(cart));
    }

    public List<Cart> queryCartList() {
        // 1.获取当前用户
        UserInfo user = UserHolder.getUserInfo();
        // 2.判断用户key是否存在
        String key = KEY_PREFIX + user.getId();
        Boolean exists = redisTemplate.hasKey(key);
        if (BooleanUtils.isFalse(exists)) {
            // 不存在，404
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        // 3.获取hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);

        // 4.取出这个用户的所有购物车
        List<String> values = hashOps.values();
        if(CollectionUtils.isEmpty(values)){
            // 不存在，404
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        // 5.存在，转换成Cart集合并返回
        return values.stream().map(json -> JsonUtils.toBean(json, Cart.class)).collect(Collectors.toList());
    }
}
